package com.secneo.appshare.adapter;

import java.util.ArrayList;

import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.secneo.appshare.R;
import com.secneo.appshare.common.AppInfo;
import com.secneo.appshare.database.AppFile;
import com.secneo.appshare.database.AppShareDatabaseHelper;

public class UserAppAdapter extends BaseAdapter {

	private Context ctx;
	private  ArrayList<AppInfo> mList; 
	private PackageManager pm;
	public UserAppAdapter(Context ctx, ArrayList<AppInfo> list) {
		this.ctx = ctx;
		this.mList = list;
		pm = ctx.getPackageManager();
	}
	
	@Override
	public int getCount() {
		// TODO Auto-generated method stub
		return mList.size();
	}

	@Override
	public Object getItem(int position) {
		// TODO Auto-generated method stub
		return mList.get(position);
	}

	@Override
	public long getItemId(int position) {
		// TODO Auto-generated method stub
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		// TODO Auto-generated method stub
		ApplicationInfo ai;
		ai = mList.get(position).appInfo;
		AppItem appItem;
		if (convertView == null) {
			View v = LayoutInflater.from(ctx).inflate(R.layout.appshare_app_item, null);
			
			appItem = new AppItem();
			appItem.mAppIcon = (ImageView)v.findViewById(R.id.ivAppIcon);
			appItem.mAppName = (TextView)v.findViewById(R.id.tvAppName);
			appItem.hiddenAppIcon=(ImageView)v.findViewById(R.id.HiddenAppIcon);
			v.setTag(appItem);
			convertView = v;
		} else {
			appItem = (AppItem)convertView.getTag();
		}
		// set icon
		Drawable dw=ai.loadIcon(pm);
		if (dw == null) {
			appItem.mAppIcon.setImageResource(R.drawable.some_app);
		} else {
			AppShareDatabaseHelper adh=new AppShareDatabaseHelper(ctx);
			AppFile aInfo=adh.getAppFileByPackageName(adh, ai.packageName);
			if(aInfo!=null)
			{
			int hidden=aInfo.getHidden();
			if(hidden==1)
			{
				appItem.hiddenAppIcon.setImageResource(R.drawable.hidden_icon);
			}
			}
			appItem.mAppIcon.setImageDrawable(dw);
		}
		// set name
		appItem.mAppName.setText(ai.loadLabel(pm));

		return convertView;
	}
	
	class AppItem {
		ImageView mAppIcon;
		ImageView  hiddenAppIcon;
		TextView mAppName;
	}

}
